package org.dromara.oce.controller.admin;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.bytedance.ads.model.FileVideoGetV2ResponseData;
import com.bytedance.ads.model.FileVideoGetV2ResponseDataListInner;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.web.core.BaseController;
import org.dromara.oce.domain.qo.GetVideoListQo;
import org.dromara.oce.domain.qo.OceMaterialQo;
import org.dromara.oce.domain.vo.OceMaterialVo;
import org.dromara.oce.mapper.OceMaterialEverydayCensusMapper;
import org.dromara.oce.service.OceMaterialService;
import org.dromara.oce.service.remote.OceanEngineThirdRemoteService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 素材
 *
 * @author dsbb
 * @date 2025-06-05
 * @module 管理平台接口
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/oce/material")
@SaIgnore
public class OceMaterialController extends BaseController {

    private final OceMaterialService oceMaterialService;
    private final OceanEngineThirdRemoteService oceanEngineThirdRemoteService;
    private final OceMaterialEverydayCensusMapper everydayCensusMapper;

    /**
     * 查询素材列表
     */
    @SaCheckPermission("oce:material:list")
    @GetMapping("/list")
    public TableDataInfo<OceMaterialVo> list(OceMaterialQo qo, PageQuery pageQuery) {
        TableDataInfo<OceMaterialVo> tableDataInfo = oceMaterialService.queryPageListCost(qo, pageQuery);
        //取出所有广告主
        Set<Long> advertiserIdSet = tableDataInfo.getRows().stream().collect(Collectors.groupingBy(OceMaterialVo::getAdvertiserId)).keySet();

        Map<Long, FileVideoGetV2ResponseDataListInner> map = new HashMap<>();
        for (Long advertiserId : advertiserIdSet) {//获取一个广告主下所有素材的视频链接
            GetVideoListQo videoListQo = new GetVideoListQo();
            videoListQo.setAccountId(qo.getAccountId());
            videoListQo.setAdvertiserId(advertiserId);
            List<Long> materialIds = tableDataInfo.getRows().stream().filter(item -> item.getAdvertiserId().longValue() == advertiserId.longValue()).map(OceMaterialVo::getMaterialId).collect(Collectors.toList());
            videoListQo.setMaterialIds(materialIds);

            FileVideoGetV2ResponseData pageData = oceanEngineThirdRemoteService.getVideoList(videoListQo);
            if (pageData.getList() != null && pageData.getList().size() > 0) {
                Map<Long, FileVideoGetV2ResponseDataListInner> map2 = pageData.getList().stream().collect(Collectors.toMap(item -> item.getMaterialId(), item -> item));
                map.putAll(map2);
            }
        }

        for (OceMaterialVo row : tableDataInfo.getRows()) {
            FileVideoGetV2ResponseDataListInner inner = map.get(row.getMaterialId());
            if(inner!=null) {
                row.setUrl(inner.getUrl());
                row.setPosterUrl(inner.getPosterUrl());
            }
        }
        return tableDataInfo;
    }

    /**
     * 同步素材
     *
     * @param qo
     * @return
     */
    @SaCheckPermission("oce:material:syncMaterial")
    @GetMapping("/syncMaterial")
    public R syncMaterial(OceMaterialQo qo) {
        if (ObjectUtils.isEmpty(qo.getStartTime()) || ObjectUtils.isEmpty(qo.getEndTime())) {
            throw new ServiceException("请选择时间范围");
        }
        qo.checkParam();
        oceMaterialService.syncMeterial(qo.getAccountId(),qo.getAdvertiserId(), qo.getStartTime(), qo.getEndTime());
        return R.ok("素材同步完成");
    }


//    /**
//     * 导出素材列表
//     */
//    @SaCheckPermission("oce:material:export")
//    @Log(title = "素材", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(OceMaterialQo qo, HttpServletResponse response) {
//        List<OceMaterialVo> list = oceMaterialService.queryList(qo);
//        ExcelUtil.exportExcel(list, "素材", OceMaterialVo.class, response);
//    }
//
//    /**
//     * 获取素材详细信息
//     *
//     * @param materialId 主键
//     */
//    @SaCheckPermission("oce:material:query")
//    @GetMapping("/{materialId}")
//    public R<OceMaterialVo> getInfo(@NotNull(message = "主键不能为空")
//                                     @PathVariable Long materialId) {
//        return R.ok(oceMaterialService.queryById(materialId));
//    }
//
//    /**
//     * 新增素材
//     */
//    @SaCheckPermission("oce:material:add")
//    @Log(title = "素材", businessType = BusinessType.INSERT)
//    @RepeatSubmit()
//    @PostMapping()
//    public R<Void> add(@Validated(AddGroup.class) @RequestBody OceMaterialBo bo) {
//        return toAjax(oceMaterialService.insertByBo(bo));
//    }
//
//    /**
//     * 修改素材
//     */
//    @SaCheckPermission("oce:material:edit")
//    @Log(title = "素材", businessType = BusinessType.UPDATE)
//    @RepeatSubmit()
//    @PutMapping()
//    public R<Void> edit(@Validated(EditGroup.class) @RequestBody OceMaterialBo bo) {
//        return toAjax(oceMaterialService.updateByBo(bo));
//    }
//
//    /**
//     * 删除素材
//     *
//     * @param materialIds 主键串
//     */
//    @SaCheckPermission("oce:material:remove")
//    @Log(title = "素材", businessType = BusinessType.DELETE)
//    @DeleteMapping("/{materialIds}")
//    public R<Void> remove(@NotEmpty(message = "主键不能为空")
//                          @PathVariable Long[] materialIds) {
//        return toAjax(oceMaterialService.deleteWithValidByIds(List.of(materialIds), true));
//    }
}
